//
//  ZYNetworkTool.swift
//  weibo007
//
//  Created by 陈宗毅 on 15/12/19.
//  Copyright © 2015年 czy. All rights reserved.
//

import UIKit

import AFNetworking

enum ZYNetworkError: Int {

    case emptyAccessToken = -1 //AccessToken没有值
    case emptyUid = -2// Uid没有值
    
    //枚举除了有成员之外，还可以有属性和方法
    //将错误code 和错误的描述，关联起来,使用计算型属性，只有get，只读计算型属性
    var errorDescription:String{
        get{
            //判断不同的类型，返回不同的错误信息
            switch self {
            case ZYNetworkError.emptyAccessToken:
                return "access_token没有值"
            case ZYNetworkError.emptyUid:
                return "Uid没有值"
            }
        }
    }
    //定义一个方法 返回一个错误，根据枚举类型不一样，返回不一样的错误
    func error() -> NSError {
        return NSError(domain: "zy.error.network", code: self.rawValue, userInfo: ["errorDescription":self.errorDescription])
    }
    
}



//网络工具类只负责请求数据，请求到数据之后，回调，不去处理数据
class ZYNetworkTool: AFHTTPSessionManager {

    
    //单例，调用默认构造方法
//    static let shareInstance:ZYNetworkTool = {
//        
//        let baseURL = NSURL(string: "https://api.weibo.com/")
//        
//        let tool = ZYNetworkTool(baseURL: baseURL)
//        
//        return tool
//
//    }()
    
    static let shareInstance:ZYNetworkTool = ZYNetworkTool()
    //不让别人访问构造方法
    private init(){
        // 没有初始化的属性
        let baseURL = NSURL(string: "https://api.weibo.com/")
        // 在构造函数里面子类不能调用父类的便利构造函数,需要调用父类的指定构造函数
        super.init(baseURL: baseURL, sessionConfiguration: nil)
        // 方法的调用必须在 super.init 只有 调用父类的super.init之后,对象才创建完毕,对象创建完毕才能调用对象的方法
        
        // 设置响应的序列化器,支持text/plain
        
        self.responseSerializer.acceptableContentTypes?.insert("text/plain")
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 授权相关
    private let client_id  = "4211991686"
    private let client_secret  = "4979c9136465c227fe45577d5d7197e4"
    
     let redirect_uri = "http://www.baidu.com"
    
    ///拼接登陆界面的URL地址
    func oAuthURL() ->NSURL{
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        //https://api.weibo.com/oauth2/authorize?client_id=4211991686&redirect_uri=http://www.baidu.com
        
        return NSURL(string: urlString)!
    }
    
    func loadAccessToken(code:String,finished: (result:[String:AnyObject]?,error:NSError?) -> ()){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //请求参数，字典
        let parametres = [
            "client_id" :client_id,
            "client_secret":client_secret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirect_uri
        ]
        
        POST(urlString, parameters: parametres, success: { (_, result) -> Void in
//            print("result: \(result)")
            let dict = result as? [String:AnyObject]
            finished(result: dict, error: nil)
            }) { (_, error) -> Void in
//            print("error:\(error)")
                finished(result: nil, error: error)
        }
    }
    
    //MAR:-加载用户信息
    func loadUserInfo(finished: (result: [String: AnyObject]?,error: NSError?) ->())
    {
        // 1.获取AccessToken,判断AccessToken是否有值
        // 守卫
        guard let access_token = ZYUserAccount.loadUserAccount()?.access_token else{
            //domain:域，自定义，表示错误的范围
            //code:自定义，一般是负数开头 -1 ，表示错误类型
            //userInfo:错误的附加信息，让别人明确错误的原因
//            let error = NSError(domain: "zy.error.network", code: -1, userInfo: ["errorDescription":"access_token没有值"])
           //定义错误枚举
//            let errorEnum = ZYNetworkError.emptyAccessToken
//            let error = NSError(domain: "zy.error.network", code: errorEnum.rawValue, userInfo: ["errorDescription":errorEnum.errorDescription])
            
            let error = ZYNetworkError.emptyAccessToken.error()
            
            //告诉调用者，网络请求出错
            finished(result: nil, error: error)
         
            return
        }

        guard let uid = ZYUserAccount.loadUserAccount()?.uid else {
           
//            let error = NSError(domain: "zy.error.network", code:-2, userInfo: ["errorDescription":"uid没有值"])
            
//            let errorEnum = ZYNetworkError.emptyUid
//            let error = NSError(domain: "zy.error.network", code: errorEnum.rawValue, userInfo: ["errorDescription":errorEnum.errorDescription])
            
            let error = ZYNetworkError.emptyUid.error()
            
            //告诉调用者，网络请求出错
            finished(result: nil, error: error)
            
          
            return
        }
        //url地址
        let urlString = "2/users/show.json"
        //请求参数
        let parameters = [
            "access_token":access_token,
            "uid":uid
        ]
        //发送请求获取用户数据
        GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            let dict = result as? [String:AnyObject]
            finished(result: dict, error: nil)
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
                
        }
    }
    
    //MARK - 获取微博数据
    func loadStatus(since_id: Int,max_id:Int, finished:(result:[String:AnyObject]?,error:NSError?) -> ()){
        
        //1.判断access_token
        guard let access_token =   ZYUserAccount.loadUserAccount()?.access_token else{
            //access_token没有值
            //创建错误 返回调用者
            let error = ZYNetworkError.emptyAccessToken.error()
            finished(result: nil, error: error)
            return
        }
        
        //2.url地址
        let urlString = "2/statuses/home_timeline.json"
        //3.请求参数
        var parameters:[String:AnyObject] = ["access_token":access_token]
        if since_id > 0 {
            parameters["since_id"] = since_id
        }else if max_id > 0 {
            parameters["max_id"] = max_id
        }
        
        let debug = false
        if debug {
            // debug模式,加载本地数据
            loadLocalStatus(finished)
            
        }else
        {
            //4.发送请求
            GET(urlString, parameters: parameters, success: { (_, result) -> Void in
                //5.闭包回调，获得到数据
                let dict = result as? [String:AnyObject]
                finished(result: dict, error: nil)
                }) { (_, error) -> Void in
                    //闭包回调，出现的错误
                    finished(result: nil, error: error)
            }
        }
    }
    
    func loadLocalStatus(finished:(result:[String:AnyObject]?,error:NSError?) -> ()){
        // 1.获取statuses.json的路径
        let path = NSBundle.mainBundle().pathForResource("statuses", ofType: "json")!
        //加载到内存中
        let data = NSData(contentsOfFile: path)!
        
        let json = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))
        let dict = json as! [String:AnyObject]
        finished(result: dict, error: nil)
        
    }
    
    // MARK: - 发送微博
    /**
    发送微博
    
    - parameter status:   微博的内容
    - parameter finished: 回调的闭包
    */
    func sendStatus(status:String,finished:(result:[String:AnyObject]?,error:NSError?) -> ()){
    
        guard let access_token = ZYUserAccount.loadUserAccount()?.access_token else {
            let error = ZYNetworkError.emptyAccessToken.error()
            finished(result: nil, error: error)
            return
        }
        // 2.url
        let urlString = "2/statuses/update.json"
        //3.请求参数
        let parameters = [
        "access_token":access_token,
            "status":status
        ]
        //发请求
        POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            let dict = result as? [String:AnyObject]
            finished(result: dict, error: nil)
            }) { (_, error) -> Void in
                finished(result: nil, error:error)
                
                
        }
    }
}
